//
//  CenterHomeViewController.m
//  ASHT_IOS
//
//  Created by 宋安安 on 14-4-2.
//  Copyright (c) 2014年 宋安安. All rights reserved.
//

#import "CenterHomeViewController.h"
#import "HomeDetailedCell.h"
#import "AFAppDotNetAPIClient.h"
#import "AFHTTPRequestOperation.h"
#import "EGOImageView.h"
#import "WebContentViewController.h"
#define degressToRadians(X) ( M_PI * (X) / 180 )

@interface CenterHomeViewController ()

@end

@implementation CenterHomeViewController
//@synthesize pageControl;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//        self.ctvdelegate=self;
        _Adaptation=YES;
        isarler=YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tabBarController makeTabBarHidden:YES];

    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *egview =
        [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(
                                                                    0.0f,
                                                                    0.0f-tableview_new.frame.size.height,
                                                                    tableview_new.frame.size.width,
                                                                    tableview_new.frame.size.height)];
        
		egview.delegate = self;
		[tableview_new addSubview:egview];
//        [self.view_Content addSubview:egview];
		_refreshHeaderView = egview;
        egview=nil;
		
	}
   [_refreshHeaderView refreshLastUpdatedDate];
	//  update the last update date
    NSString *url=@"phone!getTplbList.action";
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *ary_success=[dic_result objectForKey:@"context"];
        
        carselTV =[[CarouselTableView alloc] initWithFrame:CGRectMake(0, 0, 160 , 320)];
        carselTV.transform=CGAffineTransformMakeRotation(degressToRadians(-90));
        carselTV.center=CGPointMake(160, 80);
        [carselTV.dic_DataSource_View removeAllObjects];
        carselTV.arr_new=[NSMutableArray arrayWithArray:ary_success];
        carselTV.ctvdelegate=self;
        [view_CarouselShow addSubview:carselTV];
        pageControl.backgroundColor = [UIColor clearColor];
        pageControl.pageIndicatorTintColor=[UIColor grayColor];
        pageControl.currentPageIndicatorTintColor=[UIColor blackColor];
        pageControl.numberOfPages = ary_success.count;
        pageControl.currentPage = 0;
        for (int i=0; i<pageControl.subviews.count; i++) {
            UIImageView* dot = [pageControl.subviews objectAtIndex:i];
            CGSize size;
            size.height = 4;     //自定义圆点的大小
            size.width = 4;      //自定义圆点的大小
            [dot setFrame:CGRectMake(dot.frame.origin.x, dot.frame.origin.y, size.width, size.width)];
        }

        [view_CarouselShow addSubview:pageControl];
        _Load=NO;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        if (isarler) {
            NSString *message=[self ErrorMessageHandling:error];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            alert=nil;
            isarler=NO;
        }
       
        _Load=YES;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
	arr_new=[[NSMutableArray alloc] init];
    [self initDataSource:0 rowcount:10];
    
    tableview_new.tableHeaderView=view_CarouselShow;

}
-(void)initDataSource :(int)startnum rowcount:(int)rowcount
{
    NSString *new_url=[NSString stringWithFormat:@"phone!getArticleList.action?categoryId=102300&startnum=%i&rowcount=%i",0,10];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFAppDotNetAPIClient sharedClient] postPath:new_url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *ary_success=[dic_result objectForKey:@"context"];
        [arr_new addObjectsFromArray:ary_success];
        [tableview_new reloadData];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        if (isarler) {
            NSString *message=[self ErrorMessageHandling:error];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            alert=nil;
            isarler=NO;
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
-(void)ScrollCarouselTableViewDelegate:(int) page
{
    [pageControl setCurrentPage:page];
    [pageControl updateCurrentPageDisplay];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        if (_Adaptation) {
            self.view_Content.frame=CGRectMake(self.view_Content.frame.origin.x,self.view_Content.frame.origin.y,self.view_Content.frame.size.width,self.view_Content.frame.size.height-20);
            _Adaptation=NO;
        }
    }
    if (_Load) {
        NSString *url=@"phone!getTplbList.action";
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
            NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
            NSArray *ary_success=[dic_result objectForKey:@"context"];
            
            carselTV =[[CarouselTableView alloc] initWithFrame:CGRectMake(0, 0, 160 , 320)];
            carselTV.transform=CGAffineTransformMakeRotation(degressToRadians(-90));
            carselTV.center=CGPointMake(160, 80);
            carselTV.arr_new=[NSMutableArray arrayWithArray:ary_success];
            carselTV.ctvdelegate=self;
            [view_CarouselShow addSubview:carselTV];
            pageControl.backgroundColor = [UIColor clearColor];
            pageControl.pageIndicatorTintColor=[UIColor grayColor];
            pageControl.currentPageIndicatorTintColor=[UIColor blackColor];
            pageControl.numberOfPages = ary_success.count;
            pageControl.currentPage = 0;
            [view_CarouselShow addSubview:pageControl];
            _Load=NO;
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
            if (isarler) {
                NSString *message=[self ErrorMessageHandling:error];
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                              message:message
                                                             delegate:nil
                                                    cancelButtonTitle:@"确定"
                                                    otherButtonTitles:nil];
                [alert show];
                alert=nil;
                isarler=NO;
            }
            _Load=YES;
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];
        arr_new=[[NSMutableArray alloc] init];
        [self initDataSource:0 rowcount:10];
        tableview_new.tableHeaderView=view_CarouselShow;
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)leftButtonClickHandler:(id)sender
{
    [self.app.viewDeckController toggleLeftViewAnimated:YES];
}


//- (CGFloat)tableView:(UITableView *)tableView  heightForHeaderInSection:(NSInteger)section
//{
//    return 160;
//}

-(IBAction)pageChange:(id)sender;
{
    [carselTV setContentOffset:CGPointMake(0,pageControl.currentPage * 320) animated:YES];
    [pageControl setCurrentPage:pageControl.currentPage];
}
#pragma mark UITable
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr_new.count;
//    return 10;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	//NSLog(@"====in 设置每行的数据=====分区＝%d 行＝%d",indexPath.section,indexPath.row);
	
	static NSString *CellIdentifier = @"Cell";
	HomeDetailedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
	{
        NSArray *nibs=[[NSBundle mainBundle] loadNibNamed:@"HomeDetailedCell" owner:self options:nil];
        if (nibs.count>0) {
            cell =[nibs objectAtIndex:0];
        }
    }
    
	//行是否允许点击事件
	tableView.allowsSelection=YES;
	//行选中的样式
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    if (arr_new.count>0) {
        cell.lab_title.text=[[arr_new objectAtIndex:indexPath.row] objectForKey:@"title"];
        cell.lab_content.text=[[arr_new objectAtIndex:indexPath.row] objectForKey:@"content"];
        [cell imageUrl:[[arr_new objectAtIndex:indexPath.row] objectForKey:@"imageUrl"]];
    }
    return cell;
}
//选中行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeDetailedCell *cell = (HomeDetailedCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self selectCell:cell];
    detailedcell=cell;
  
    WebContentViewController *webVC = [[WebContentViewController alloc] initWithNibName:XIB_Version(@"WebContentViewController") bundle:nil];
   
    webVC.titleStr = @"首页";
    
    webVC.requestStr = [NSString stringWithFormat:SERVER_BASICE_URL@"phone!getArticle.action?articleId=%@",[[arr_new objectAtIndex:indexPath.row] objectForKey:@"articleId"]];
    webVC.key=[[arr_new objectAtIndex:indexPath.row] objectForKey:@"title"];
    [self.app.viewDeckController.navigationController pushViewController:webVC animated:YES];

}
-(void)selectCell:(HomeDetailedCell *) cell
{
    if (detailedcell==cell) {
        return;
    }
    [detailedcell.image_back setHighlightedImage:cell.image_back.highlightedImage];
    [detailedcell.image_back setImage:cell.image_back.image];
    UIImage *image_h=cell.image_back.highlightedImage;
    [cell.image_back setHighlightedImage:cell.image_back.image];
    [cell.image_back setImage:image_h];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = NO;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:tableview_new];
	
}
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	//[delegate pullUpdateData];
    //	[self reloadTableViewDataSource];
    isarler=YES;
	[arr_new removeAllObjects];
    [self initDataSource:0 rowcount:10];
//    newsLong=YES;
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

- (void)egoRefreshTableHeaderDidTriggerToBottom
{
//    [self initDataSource:arr_new.count rowcount:5];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    isarler=YES;
    
}
@end
